<%--
  Created by IntelliJ IDEA.
  User: houxianghua
  Date: 2015/7/21
  Time: 8:59
  To change this template use File | Settings | File Templates.
--%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="/WEB-INF/jsp/component/common.jsp" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title></title>
    <%@include file="/WEB-INF/jsp/component/commonHead.jsp" %>
    <%@include file="/WEB-INF/jsp/component/commonBottom.jsp" %>
    <style>
        .text-center{
            text-align:center;
        }
    </style>
</head>
<%--<body onresize="reSizeParentIframe()" onload="reSizeParentIframe();">--%>
<body>
    <div class="row">
        <div class="col-lg-12">
            <h1 class="page-header">大区管理</h1>
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
    <div class="row">
        <div class="col-lg-12">
            <div class="panel panel-default">
                <div class="panel-heading">
                    名称:<input type="text" id="name" name="name"/>
                    <button id="query" class="mk_butt" >查询</button>
                        <%--<button id="query" type="button" class="btn btn-outline btn-success">查询</button>--%>
                </div>
                <!-- /.panel-heading -->
                <div class="panel-body">
                    <div class="dataTable_wrapper">
                        <table id="example" class="table table-striped table-bordered table-hover" width="100%">
                            <thead>
                            <tr align="left">
                                <th><input id="all_id" type="checkbox"></th>
                                <th>大区名称</th>
                                <th>辖区管理</th>
                            </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
                <!-- /.panel-body -->
            </div>
            <!-- /.panel -->
        </div>
        <!-- /.col-lg-12 -->
    </div>

    <!-- 新增 -->
    <div class="modal fade" id="addModal">
        <div class="modal-dialog" >
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button>
                    <h4 class="modal-title">大区新增</h4>
                </div>
                <div class="modal-body">
                    <iframe id="addIframe" name="addIframe" width="100%" height="100%" frameborder="0" ></iframe>
                </div>
                <%--<div class="modal-footer">--%>
                    <%--<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>--%>
                    <%--<button type="button" class="btn btn-primary" id="submit_add">保存</button>--%>
                <%--</div>--%>
            </div>
        </div>
    </div>
    <!-- 修改 -->
    <div class="modal fade" id="updateModal">
        <div class="modal-dialog" >
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button>
                    <h4 class="modal-title">大区修改</h4>
                </div>
                <div class="modal-body">
                    <iframe id="updateIframe" name="updateIframe" width="100%" height="100%" frameborder="0" ></iframe>
                </div>
                <%--<div class="modal-footer">--%>
                    <%--<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>--%>
                    <%--<button type="button" class="btn btn-primary" id="submit_update">保存</button>--%>
                <%--</div>--%>
            </div>
        </div>
    </div>
    <!-- 辖区修改 -->
    <div class="modal fade" id="popedomModal">
        <div class="modal-dialog" >
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button>
                    <h4 class="modal-title">辖区修改</h4>
                </div>
                <div class="modal-body">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="submit_popedom">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        var provinceFindArea=new Object();
        var idSelectAllExist = [];
        var table;
        var parentWindowData= parent.top;
        function initTable() {
            table = $("#example").DataTable({
                "dom": "<'row'<'col-xs-2'l><'#mytool.col-xs-10'><'col-xs-6'f>r>" +
                "t" +
                "<'row'<'col-xs-6'i><'col-xs-6'p>>",
                "bFilter": false,//去掉搜索框
                "bAutoWidth": true, //自适应宽度
                "sPaginationType" : "full_numbers",
//                "bDestroy" : true,
//              "asStripeClasses": [ 'strip1', 'strip2', 'strip3' ],//设置斑马条（奇偶行）的css class
                "ordering": false,//是否允许Datatables开启排序
                "bProcessing" : true,
                "bServerSide" : true,
                "sAjaxSource" : "${URL_ADM_AREA_SEARCH}",
                "sAjaxDataProp": "dataList",//查询后，返回的集合
                "fnServerData": function ( sSource, aoData, fnCallback ) {  //查询条件
                    aoData.push(
                            { "name": "name", "value": $("#name").val() }
                    );
                    $.ajax( {
                        "dataType": 'json',
                        "url": sSource,
                        "type":'post',
                        "data": aoData,
                        "success": fnCallback,
                        "complete":function(data){
                            var dataTemp=data.responseText;
                            var dataset = $.parseJSON(dataTemp);
                            var allAreaData=dataset.allData;
                            InitAreaCode(allAreaData);
//                            alert("xyc");
                        }
                    } );

                },
                "aoColumns" : [ {
                    "targets": -1,
                    "data": null,
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        $(nTd).html('' +
                                '&nbsp;&nbsp;<input name="id" value="'+oData.largeAreaCode+'" type="checkbox" onClick="isCheckedAll()">' +
                                '');
                    }
                }, {
                    "mDataProp" : "largeAreaName"
                }, {
                    "mDataProp" : "names",
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        var popedomButt = "";
                        <shiro:hasPermission name="+areaProvince+6">
                        popedomButt += '<div style="float:right; width: 170px;">'
                                + '<input type="button" class="btn btn-outline btn-success" value="编辑" onclick="setPopedomModal(\''+oData.largeAreaCode+'\',\''+oData.ids+'\')" >'
                                + '</div>';
                        </shiro:hasPermission>
                        $(nTd).html(sData+popedomButt);
                    }
                }
                ],
                "oLanguage" : {
                    "sProcessing" : "正在加载中......",
                    "sLengthMenu" : "每页显示 _MENU_ 条记录",
                    "sZeroRecords" : "没有数据！",
                    "sEmptyTable" : "无数据存在！",
                    "sInfo" : "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
                    "sInfoEmpty" : "显示0到0条记录",
                    "sInfoFiltered" : "数据表中共为 _MAX_ 条记录",
                    //"sSearch" : "搜索",
                    "oPaginate" : {
                        "sFirst" : "首页",
                        "sPrevious" : "上一页",
                        "sNext" : "下一页",
                        "sLast" : "末页"
                    }
                },
                initComplete: function () {
                    <shiro:hasPermission name="+area+8">
                    $("#mytool").append('<button id="delete_butt" type="button" class="btn btn-outline btn-success" style="float:right;">删除</button>');
                    $("#delete_butt").on("click", toDelete);
                    </shiro:hasPermission>
                    <shiro:hasPermission name="+area+4">
                    $("#mytool").append('<button id="update_butt" type="button" class="btn btn-outline btn-success" style="float:right;">修改</button>');
                    $("#update_butt").on("click", toUpdate);
                    </shiro:hasPermission>
                    <shiro:hasPermission name="+area+2">
                    $("#mytool").append('<button id="add_butt" type="button" class="btn btn-outline btn-success" style="float:right;">新增</button>');
                    $("#add_butt").on("click", toAdd);
                    </shiro:hasPermission>
                }
            });
        }

        //新增
        function toAdd(){
            window.parent.showModelIframe("${URL_ADM_AREA_TOADD}","新增大区",800,400);
        }

        //修改
        function toUpdate(){
            var checkedArray = getCheckedArray();
            if(checkedArray.length!=1){
                top.bootbox.dialog({
                    message: "请选中一项数据",
                    buttons: {
                        OK: {
                            label: "确定",
                            className: "btn-primary"
                        }
                    }
                });
                return false;
            }
            window.parent.showModelIframe("${URL_ADM_AREA_TOUPDATE}?largeAreaCode=" +checkedArray[0],"修改大区",800,400);
        }

        //删除
        function toDelete(){
            var checkedArray = getCheckedArray();
            var ids = "";
            if(checkedArray.length==0){
                top.bootbox.dialog({
                    message: "请选中至少一项数据",
                    buttons: {
                        OK: {
                            label: "确定",
                            className: "btn-primary"
                        }
                    }
                });
                return false;
            }else{
                for(var i=0; i<checkedArray.length;i++){
                    ids += checkedArray[i]+",";
                }
                ids = ids.substring(0,ids.length-1);
            }
            top.bootbox.dialog({
                message: "确定删除此项？",
                buttons: {
                    OK: {
                        label: "确定",
                        className: "btn-primary",
                        callback: function () {
                            $.ajax({
                                url:'${URL_ADM_AREA_DELETES}',//删除地址
                                type:'post',
                                data:{ids:ids},
                                async : false, //默认为true 异步
                                dataType: "json",
                                error:function(){
                                    alert('error');
                                },
                                success:function(data){
                                    refreshTable();
                                }
                            });
                        }
                    },
                    Cancel: {
                        label: "取消",
                        className: "btn-default"
                    }
                }
            });
        }

        //多选按钮
        $("#all_id").click(function(){
            if(this.checked){
                $("input[name='id']").each(function(){
                    $(this)[0].checked = true;
                });
            }else{
                $("input[name='id']").each(function(){
                    $(this)[0].checked = false;
                });
            }
        });

        //判断是否已经全选
        function isCheckedAll(){
            var isCheckAll = true;
            $("input[name='id']").each(function(){
                if(!this.checked){
                    isCheckAll = false;
                }
            });
            if(isCheckAll){
                $("#all_id")[0].checked = true;
            }else{
                $("#all_id")[0].checked = false;
            }
        }

        function getCheckedArray(){
            var checkedArray = [];
            $("input[name='id']").each(function(){
                if(this.checked){
                    checkedArray.push(this.value);
                }
            });
            return checkedArray;
        }

//        //新增提交  调用子级页面新增方法
//        $("#submit_add").click(function(){
//            $("#submit_add").attr('disabled',"true");
//            document.getElementById('addIframe').contentWindow.doAdd();
//        });
//
//        //修改提交  调用子级页面修改方法
//        $("#submit_update").click(function(){
//            document.getElementById('updateIframe').contentWindow.doUpdate();
//        });

        //关闭弹出框,并刷新列表
        function closeModal(flag){
//            parentWindowData.$('#'+flag+"Modal").modal('hide');
            parentWindowData.$("#dialog-Show").modal('hide');
            refreshTable();
        }

        //只关闭弹出框，不刷新
        function simpleCloseModal(flag){
//            $('#'+flag+"Modal").modal('hide');
            parentWindowData.$("#dialog-Show").modal('hide');
        }


        //查询
        $("#query").click(function() {
            refreshTable();
        });

        //刷新table数据
        function refreshTable(){
            table.ajax.reload();
            //重置全选按钮
            $("#all_id")[0].checked = false;
        }

        $(document).ready(function() {
            initTable();
        });

        //初始化全部的区域编码
        function InitAreaCode(areaAllCode){
            provinceFindArea=new Object;
            for (var i = 0; i < areaAllCode.length; i++) {
                var oneAreaCode=areaAllCode[i];
                var idArrExistStr = oneAreaCode.ids.split(",");//属于该大区的辖区code数组（String类型)
                for (var j = 0; j < idArrExistStr.length; j++){
                    provinceFindArea[Number(idArrExistStr[j])]=oneAreaCode.largeAreaName;
                }

            }
        }

        /**
         * 设置辖区绑定模态框内容、样式， 并显示
         * areaCodes：辖区code
         * */
        function setPopedomModal(largeAreaCode, ids){
            var idArrExistStr = ids.split(",");//属于该大区的辖区code数组（String类型)
            var idArrExist = [];//属于该大区的辖区code数组
            for (var i = 0; i < idArrExistStr.length; i++) {
                idArrExist.push(Number(idArrExistStr[i]));
            }
            idSelectAllExist=idArrExist;
            var popedomModalHtml = '<form id="popedomForm" class="form-horizontal" method="post" >' +
                    '<input type="hidden" id="largeAreaCode" name="largeAreaCode" value="'+largeAreaCode+'" />' +
                    '<div class="form-group">';
            <c:forEach items="${provinceList}" var="area">
                if($.inArray(${area.id},idArrExist)>=0){
                    //属于该大区的辖区
                    popedomModalHtml += '<div class="col-sm-4"><label class="checkbox-inline"><input type="checkbox" checked="checked" name="ids" onclick="decTip(\'${area.id}\')" value="${area.id}">${area.name}</label></div>';
                }else{
                    //不属于该大区的辖区
                    popedomModalHtml += '<div class="col-sm-4"><label class="checkbox-inline"><input type="checkbox" name="ids" onclick="decTip(\'${area.id}\')" value="${area.id}">${area.name}</label></div>';
                }
            </c:forEach>
            //列出不属于该大区的辖区
            <%--<c:forEach items="${provinceList}" var="area">--%>
                <%--if($.inArray('${area.code}',idArrExist)<0){--%>
                    <%--PopedomModalHtml += '<div class="col-sm-4"><label class="checkbox-inline"><input type="checkbox" name="areaCodes" value="${area.code}">${area.name}</label></div>';--%>
                <%--}--%>
            <%--</c:forEach>--%>
            popedomModalHtml += '</div></form>';
            $("#popedomModal .modal-body").html(popedomModalHtml);//设置模态框内容
            parentWindowData.$("#dialog-Show").html($('#popedomModal').html());
            parentWindowData.$("#dialog-Show input[type='checkbox']").each(function(){
                $(this).click(function(){ decTip($(this).prop("value"));});
            });

            parentWindowData.$("#dialog-Show #submit_popedom").click(function(){
                submit_popedom_function();
            })

            parentWindowData.$('#dialog-Show').modal({show: true, backdrop: 'static'});
        /*    $("#popedomModal .modal-body").html(popedomModalHtml);//设置模态框内容
            $('#popedomModal').modal({ show: true, backdrop: 'static' });//显示模态框*/
        }

        function decTip(selectId){
            if($.inArray(selectId,idSelectAllExist)>=0){
                return;
            }else{
                if(parentWindowData.$(".modal-dialog  input[value="+selectId+"]").prop("checked") && provinceFindArea[selectId]!=undefined){
                    parentWindowData.bootbox.dialog({
//                message: "医院："+rowData.hospName,
//                title: "确定删除此项？",
                        message: "该区域已经被"+provinceFindArea[selectId]+"选中是否需要继续选择该大区信息",
                        buttons: {
                            OK: {
                                label: "确定",
                                className: "btn-primary"
                            },
                            Cancel: {
                                label: "取消",
                                className: "btn-default",
                                callback: function () {
                                    parentWindowData.$(".modal-dialog  input[value="+selectId+"]").prop("checked", "");
                                }
                            }
                        }
                    });
                }
            }
        }

        function submit_popedom_function(){
            $.ajax({
                url:'${URL_ADM_AREA_POPEDOMUPDATE}',
                type:'post',
                data:parentWindowData.$('#popedomForm').serialize(),
                async : false, //默认为true 异步
                dataType: "json",
                error:function(){
                    alert('error');
                },
                success:function(data){
                    closeModal("popedom");
                }
            });
        }

        //修改辖区提交
        $("#submit_popedom").click(function(){
            $.ajax({
                url:'${URL_ADM_AREA_POPEDOMUPDATE}',
                type:'post',
                data: parentWindowData.$('#popedomForm').serialize(),
                async : false, //默认为true 异步
                dataType: "json",
                error:function(){
                    alert('error');
                },
                success:function(data){
                    closeModal("popedom");
                }
            });
        });

    </script>
</body>
</html>